from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from models import *
import flickrapi

def rsd(request):
    response = render_to_response("rsd.xml", context_instance=RequestContext(request))
    response['Content-Type'] = 'text/xml; charset=utf-8'
    return  response

def wlmmanifest(request):
    response = render_to_response("wlmmanifest.xml", context_instance=RequestContext(request))
    response['Content-Type'] = 'text/xml; charset=utf-8'
    return  response

def storemedia(filename, bits, type):
    api_key='####key####'
    secret = '####your secret####'
    flickr = flickrapi.FlickrAPI(api_key = api_key, secret = secret, token = '### token ####', cache=False)
    f = flickr.uploadbits(filename, bits, type)
    res = flickr.photos_getSizes(photo_id = f.photoid[0].text)
    return res.sizes[0].size[3].attrib['source']

def xmlrpc_handler(request):
    servername = request.META['SERVER_NAME']
    blog = Blog.get(servername)   
    dispatcher = MetaWeblogAPIDispatcher(blog)
    response = HttpResponse()
    if len(request.POST):
        response.write(dispatcher._marshaled_dispatch(request.raw_post_data))
        return response
    else:
        return HttpResponse('Error')


class MetaWeblogAPIDispatcher(SimpleXMLRPCDispatcher):
    def __init__(self, blog):
        SimpleXMLRPCDispatcher.__init__(self, False, 'utf-8')  
        self.blog = blog   
        self.funcs = {'blogger.getUserInfo': self.blogger_getUserInfo,
                    'blogger.getUsersBlogs': self.blogger_getUsersBlogs,
                    'metaWeblog.getRecentPosts': self.metaWeblog_getRecentPosts,
                    'blogger.deletePost': self.blogger_deletePost,
                    'metaWeblog.getPost': self.metaWeblog_getPost,
                    'metaWeblog.editPost': self.metaWeblog_editPost,
                    'metaWeblog.newPost':self.metaWeblog_newPost,
                    'metaWeblog.newMediaObject': self.metaWeblog_newMediaObject,
                    'metaWeblog.getCategories': self.metaWeblog_getCategories,
                    } 
         
    def blogger_getUserInfo(self, appkey, username, password):
        if (password != '#### password ####'):           # you should add better implementation for password check.
            raise Exception, 'access denied'   
        return {
                'userid': 'mao',
                'firstname':'Robert',
                'lastname': 'Mao',
                'url': 'http://new.robertmao.com/',
                'email': 'zhihong.mao@gmail.com',
                'nickname': 'mao'
                }
       
    def blogger_getUsersBlogs(self, appkey, username, password):  
        if (password != 'MAO#&(!'):
            raise Exception, 'access denied'   
        return [{
                'url': 'http://localhost:8080/',
                'blogid': 'new.robertmao.com',
                'blogName': self.blog.title,
                },
                ]  
       
    def blogger_deletePost(self, appkey, postid, username, password, publish):   
        return Post.delete_post(self.blog, postid)
   
    def metaWeblog_getRecentPosts(self, blogid, username, password, num):
        return [{
                 'postid':post.postid,
                 'DateTime':post.published_when,
                 'title':post.title,
                 'description': unicode(post.body),
                 'categories': [unicode(t) for t in post.tags],
                 'publish': not post.isdraft,
                 } for post in  Post.get_all(self.blog).fetch(num)]
   
    def metaWeblog_getPost(self, postid, username, password):
        post = Post.get(self.blog, postid).get()
        return {'postid':post.postid,
                'dateCreated':post.published_when,
                'title': post.title,
                'description': unicode(post.body),
                'categories': [unicode(t) for t in post.tags],
                'publish': not post.isdraft
                }
   
    def metaWeblog_editPost(self, postid, username, password, content, publish):
        post = Post.get(self.blog, postid).get()  
        if (post is not None):
            if (content['title']):
                post.title = content['title']
            if content['description'] :
                post.body = content['description']
            if  content['categories']:
                post.tags = [db.Category(t) for t in content['categories']]
            post.put()
            return True;
        return False;
   
    def metaWeblog_newPost(self, blogid, username, password, content, publish):
         post = Post(blog = self.blog, title = content['title'], body = content['description'], tags = [db.Category(t) for t in content['categories']], postid=0)
         return post.save()

    def metaWeblog_newMediaObject(self, blogid, username, password, file):
        mediaurl = storemedia(file['name'], file['bits'], file['type'])
        return { 'url': mediaurl}
   
    def metaWeblog_getCategories(self, blogid, username, password):
        tags = Post.get_all_tags(self.blog)
        return [{'description': t,
                 'title': t} for t in tags]